package com.bjqg.bjqg01.bjqg.fragment;/**
 * Created by dell on 2017/4/5/0005.
 */

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.ajguan.library.EasyRefreshLayout;
import com.ajguan.library.LoadModel;
import com.bjqg.bjqg01.bjqg.R;
import com.bjqg.bjqg01.bjqg.activity.AboutUsActivity;
import com.bjqg.bjqg01.bjqg.activity.ContactInformationActivity;
import com.bjqg.bjqg01.bjqg.activity.EntrusManageActibity;
import com.bjqg.bjqg01.bjqg.activity.NoticeActivity;
import com.bjqg.bjqg01.bjqg.activity.OnlineMessageActivity;
import com.bjqg.bjqg01.bjqg.activity.ReportFindActivity;
import com.bjqg.bjqg01.bjqg.activity.SampleMethodActivity;
import com.bjqg.bjqg01.bjqg.activity.longrange.activity.LongRangeActivity;
import com.bjqg.bjqg01.bjqg.activity.seekprice.activity.SeekPrice;
import com.bjqg.bjqg01.bjqg.adapter.HomeAdapter;
import com.bjqg.bjqg01.bjqg.bean.HomeBean;
import com.bjqg.bjqg01.bjqg.bean.NoticeBean;
import com.bjqg.bjqg01.bjqg.utils.Constant;
import com.bjqg.bjqg01.bjqg.utils.GlideImageLoader;
import com.bjqg.bjqg01.bjqg.view.LooperTextView;
import com.brioal.adtextviewlib.entity.AdEntity;
import com.brioal.adtextviewlib.view.ADTextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.yzq.zxinglibrary.android.CaptureActivity;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * created by LiChengalin at 2017/4/5/0005
 */
public class FirstFragment extends BaseFragment implements View.OnClickListener {
    private WindowManager windowManager;
    private Banner banner;
    private LooperTextView looperview;
    private RecyclerView rvHome;
    private View viewinflte;
    private LinearLayout sampleMehtod;
    private LinearLayout notice;
    private LinearLayout priceQuery;
    private LinearLayout onlineEntrust;
    private LinearLayout onlinePay;
    private LinearLayout reportQuery;
    private LinearLayout cotactWay;
    private LinearLayout reportRecognition;
    private LinearLayout creditEvaluation;
    private LinearLayout onlineMessage;
    private LinearLayout complaintProposal;
    private LinearLayout aboutUs;
    private int REQUEST_CODE_SCAN = 111;
    private ImageView tvScan;
    private String[] split1;
    private String yema = "1";
    private HomeAdapter homeAdapter;
    View view;

    public static FirstFragment newInstance() {

        Bundle bundle = new Bundle();

        FirstFragment fragment = new FirstFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        windowManager = getActivity().getWindowManager();
        initView();
        super.onActivityCreated(savedInstanceState);
    }

    private void initView() {

        rvHome = (RecyclerView) view.findViewById(R.id.rv_home);
        tvScan = (ImageView) view.findViewById(R.id.tv_scan);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvHome.setLayoutManager(layoutManager);

        ArrayList<HomeBean> gethombean = gethombean();
        homeAdapter = new HomeAdapter(gethombean);
        viewinflte = View.inflate(getActivity(), R.layout.item_new_home_header, null);
        initBanner();

        homeAdapter.addHeaderView(viewinflte);


        //轮播图

        //滚动标题
//        looperviewShow();


        // pull-up loading
        pullUpLoading(homeAdapter);
//        pullUpLoad(homeAdapter);


        initData();

        notice = (LinearLayout) viewinflte.findViewById(R.id.notice_new_home);
        priceQuery = (LinearLayout) viewinflte.findViewById(R.id.price_query_new_home);
        sampleMehtod = (LinearLayout) viewinflte.findViewById(R.id.sample_method_new_home);
        onlineEntrust = (LinearLayout) viewinflte.findViewById(R.id.online_entrust_new_home);
        onlinePay = (LinearLayout) viewinflte.findViewById(R.id.online_pay_new_home);
        reportQuery = (LinearLayout) viewinflte.findViewById(R.id.report_query_new_home);
        cotactWay = (LinearLayout) viewinflte.findViewById(R.id.contact_way_new_home);
        reportRecognition = (LinearLayout) viewinflte.findViewById(R.id.report_recognition_new_home);
        creditEvaluation = (LinearLayout) viewinflte.findViewById(R.id.credit_evaluation_new_home);
        onlineMessage = (LinearLayout) viewinflte.findViewById(R.id.online_message_new_home);
        complaintProposal = (LinearLayout) viewinflte.findViewById(R.id.complaint_proposal_new_home);
        aboutUs = (LinearLayout) viewinflte.findViewById(R.id.about_us_new_home);

        tvScan.setOnClickListener(this);
        notice.setOnClickListener(this);
        priceQuery.setOnClickListener(this);
        sampleMehtod.setOnClickListener(this);
        onlineEntrust.setOnClickListener(this);
        onlinePay.setOnClickListener(this);
        reportQuery.setOnClickListener(this);
        cotactWay.setOnClickListener(this);
        reportRecognition.setOnClickListener(this);
        creditEvaluation.setOnClickListener(this);
        onlineMessage.setOnClickListener(this);
        complaintProposal.setOnClickListener(this);
        aboutUs.setOnClickListener(this);

        rvHome.setAdapter(homeAdapter);

    }

    private void initData() {

        getokgo(yema);
//        showADTextView();
    }

    private void pullUpLoad(final HomeAdapter homeAdapter) {

        homeAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                rvHome.postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        if (mCurrentCounter >= TOTAL_COUNTER) {
                        if (false) {
                            //数据全部加载完毕
                            homeAdapter.loadMoreEnd();
                        } else {
//                            if (isErr) {
                            if (true) {
                                //成功获取更多数据
//                                homeAdapter.addData(DataServer.getSampleData(PAGE_SIZE));
//                                mCurrentCounter = homeAdapter.getData().size();
                                homeAdapter.loadMoreComplete();
                            } else {
                                //获取更多数据失败
//                                isErr = true;
//                                Toast.makeText(PullToRefreshUseActivity.this, R.string.network_err, Toast.LENGTH_LONG).show();
                                homeAdapter.loadMoreFail();

                            }
                        }
                    }
                }, 1000);
            }
        });
    }

    private void pullUpLoading(final HomeAdapter homeAdapter) {
        final EasyRefreshLayout easyRefreshLayout = (EasyRefreshLayout) view.findViewById(R.id.refresh_home_layout);
        easyRefreshLayout.setLoadMoreModel(LoadModel.COMMON_MODEL);
        easyRefreshLayout.addEasyEvent(new EasyRefreshLayout.EasyEvent() {
            @Override
            public void onLoadMore() {

                easyRefreshLayout.loadMoreComplete(new EasyRefreshLayout.Event() {
                    @Override
                    public void complete() {
//                                homeAdapter.getData().addAll(list);
//                                homeAdapter.notifyDataSetChanged();
                        Toast.makeText(getActivity(), "没有更多数据", Toast.LENGTH_SHORT).show();
                    }
                }, 0);

            }

            @Override
            public void onRefreshing() {
                easyRefreshLayout.refreshComplete();

            }
        });

    }

    private void showADTextView(List<NoticeBean.DsBean> ds) {

        ADTextView mADTextView = (ADTextView) viewinflte.findViewById(R.id.ad_textview);//公告轮播
        ArrayList<AdEntity> mList = new ArrayList<>();
        for (int i = 0; i < ds.size(); i++) {
            NoticeBean.DsBean dsBean = ds.get(i);
            String s = dsBean.getTimeStr().toString();
//            Date date = strToDateLong(s);
//            String s1 = dateToStr(date);
//            Log.e("showADTextView: ", s1+"");
//            mList.add(new AdEntity("", dsBean.getTimeStr()+" "+dsBean.getContentStr(), dsBean.getContentStr()));
            mList.add(new AdEntity("", s.substring(0, 9).toString() + " " + dsBean.getContentStr(), dsBean.getContentStr()));
        }

//        mList.add(new AdEntity("前缀2", "内容2", "连接2"));
//        mList.add(new AdEntity("前缀3", "内容3", "连接3"));
//        mList.add(new AdEntity("前缀4", "内容4", "连接4"));
//        mADTextView.setFrontColor(Color.RED);
//        mADTextView.setBackColor(Color.BLACK);
//        mADTextView.setContentTextSize(mADTextView.getHeight()-5);
//        mADTextView.setFrontTextSize(50);
//        mADTextView.setContentTextSize(50);
//        mADTextView.setTextSize(50);
        mADTextView.setBackColor(getResources().getColor(R.color.mk_text_color));
        mADTextView.setTexts(mList);
        mADTextView.setOnItemClickListener(new ADTextView.OnItemClickListener() {

            @Override
            public void onClick(String mUrl) {

            }
        });
    }

    public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    public static String dateToStr(java.util.Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(dateDate);
        return dateString;
    }

    private void getokgo(String pagenum) {

    }

    private String getUrl(String pagenum) {
        String url = Constant.BASEURL + Constant.SELECTGONGGAO + "?yema="
                + pagenum + "&sqlwhere=";
        return url;
    }

    private Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    NoticeBean refreshinfo = msg.getData().getParcelable("noticeBean");
//                    yema = refreshinfo.getPageNum().toString();
//                    int size = refreshinfo.getDs().size();
                    showADTextView(refreshinfo.getDs());
                    rvHome.setAdapter(homeAdapter);
                    break;
            }

        }
    };

    private void looperviewShow() {
        looperview = (LooperTextView) viewinflte.findViewById(R.id.looperview);
        //通知滚动
        looperview.setTipList(generateTips());
    }

    private void initBanner() {
        Integer[] images = {R.mipmap.slide_vp, R.mipmap.slide_2_vp, R.mipmap.slide_3_vp};
        ArrayList<Integer> imageViews = new ArrayList<>();
        for (int i = 0; i < images.length; i++) {
            imageViews.add(images[i]);
        }
        banner = (Banner) viewinflte.findViewById(R.id.banner);
//        banner = (Banner) findViewById(R.id.banner);
        ViewGroup.LayoutParams layoutParams = banner.getLayoutParams();
        layoutParams.height = getheigh() / 4;
//        layoutParams.width=getwith()/2;
        banner.setLayoutParams(layoutParams);
        //设置图片集合
        banner.setImages(imageViews);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.RIGHT);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    public int getwith() {
        int width = windowManager.getDefaultDisplay().getWidth();
        return width;
    }

    public int getheigh() {
        int height = windowManager.getDefaultDisplay().getHeight();
        return height;
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
//        looperview.stopNestedScroll();
    }

    private ArrayList<String> generateTips() {
        ArrayList<String> tips = new ArrayList<>();
        for (int i = 0; i < 50; i++) {

            tips.add("这有通知:" + i);
        }

        return tips;
    }

    private ArrayList<HomeBean> gethombean() {
        ArrayList<HomeBean> tips = new ArrayList<>();
        for (int i = 0; i < 50; i++) {

//            tips.add("公告列表"+i);
            tips.add(new HomeBean(i, "389.3亿！中国中铁重大工程中标公告" + i, i % 2 + 1));
        }

        return tips;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            //公告
            case R.id.notice_new_home:
                Intent intent = new Intent(getActivity(), NoticeActivity.class);
                startActivity(intent);
                break;
            //价格查询
            case R.id.price_query_new_home:
//                Intent intent1 = new Intent(context, PriceInquiryActivity.class);
//                startActivity(intent1);
                Intent intent1 = new Intent(getActivity(), SeekPrice.class);
                startActivity(intent1);
                break;
            //取样方法
            case R.id.sample_method_new_home:
                Intent intent2 = new Intent(getActivity(), SampleMethodActivity.class);
                startActivity(intent2);
                break;
            //网上委托
            case R.id.online_entrust_new_home:
                Intent intent3 = new Intent(getActivity(), LongRangeActivity.class);
                startActivity(intent3);
                break;
            //网上支付-委托管理
            case R.id.online_pay_new_home:
                Intent intent4 = new Intent(getActivity(), EntrusManageActibity.class);
                startActivity(intent4);
                break;
            //报告查询
            case R.id.report_query_new_home:
                Intent intent5 = new Intent(getActivity(), ReportFindActivity.class);
                startActivity(intent5);
                break;
            //联系方式
            case R.id.contact_way_new_home:
                Intent intent6 = new Intent(getActivity(), ContactInformationActivity.class);
                startActivity(intent6);
                break;
            //右上角扫描
            case R.id.tv_scan:
                //报告识别
            case R.id.report_recognition_new_home:
                if (Build.VERSION.SDK_INT >= 22) {
                    if (ContextCompat.checkSelfPermission(getActivity(),
                            android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        //先判断有没有权限 ，没有就在这里进行权限的申请
                        ActivityCompat.requestPermissions(getActivity(),
                                new String[]{android.Manifest.permission.CAMERA}, 1);

                    } else {
//                        说明已经获取到摄像头权限了 想干嘛干嘛
                        Intent intent7 = new Intent(getActivity(), CaptureActivity.class);
//                        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                        startActivityForResult(intent7, REQUEST_CODE_SCAN);
                    }
                } else {

//                    这个说明系统版本在6.0之下，不需要动态获取权限。
                    Intent intent7 = new Intent(getActivity(), CaptureActivity.class);
//                    intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                    startActivityForResult(intent7, REQUEST_CODE_SCAN);

                }
                break;
            //诚信评价
            case R.id.credit_evaluation_new_home:
//                Intent intent8 = new Intent(context, SampleMethodActivity.class);
//                startActivity(intent8);
                Toast.makeText(getActivity(), "此功能暂没开发", Toast.LENGTH_LONG).show();
                break;
            //在线留言
            case R.id.online_message_new_home:
                Intent intent9 = new Intent(getActivity(), OnlineMessageActivity.class);
                intent9.putExtra("OnlineMessageActivity", "在线留言");
                startActivity(intent9);
                break;
            //投诉建议
            case R.id.complaint_proposal_new_home:
//                Intent intent10 = new Intent(context, SampleMethodActivity.class);
//                startActivity(intent10);
                Toast.makeText(getActivity(), "此功能暂没开发", Toast.LENGTH_LONG).show();

                break;
            //关于我们
            case R.id.about_us_new_home:
                Intent intent11 = new Intent(getActivity(), AboutUsActivity.class);
                startActivity(intent11);
//                Toast.makeText(context, "此功能暂没开发", Toast.LENGTH_LONG).show();
                break;
        }
    }


}
